package com.dwd.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.dwd.basic.constant.AlipayConfig;
import com.dwd.basic.utils.AjaxResult;
import com.dwd.pay.mapper.AlipayInfoMapper;
import com.dwd.pay.pojo.AlipayInfo;
import com.dwd.pay.service.IPayBillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description: TODO
 * @Author 汶狄
 * @Date 2021/1/28 14:53
 * @Version 1.0
 */
@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private AlipayInfoMapper alipayInfoMapper;
    @Autowired
    private IPayBillService payBillService;

    /**
     * 修改状态
     *
     * @param request
     * @return
     */
    @RequestMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request) {
        try {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            String app_id = params.get("app_id");
            AlipayInfo alipayInfo = alipayInfoMapper.queryAliPayInfoByAppId(app_id);
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipay_public_key(), AlipayConfig.charset, AlipayConfig.sign_type);

            //——请在这里编写您的程序（以下代码仅作参考）——
            /* 实际验证过程建议商户务必添加以下校验：
            1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
            //验证成功
            if (signVerified) {
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //交易状态
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
                if (trade_status.equals("TRADE_SUCCESS")) {
                    //修改状态时间支付宝交易号
                    payBillService.updatePayBill(out_trade_no, trade_no);
                    return "success";
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }

    /**
     * 跳转界面
     *
     * @param request
     * @return
     */
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request) {
        try {
            //获取支付宝GET过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            String app_id = params.get("app_id");
            AlipayInfo alipayInfo = alipayInfoMapper.queryAliPayInfoByAppId(app_id);
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipay_public_key(), AlipayConfig.charset, AlipayConfig.sign_type);
            //——请在这里编写您的程序（以下代码仅作参考）——
            if (signVerified) {
                return "redirect:http://localhost:8002/success.html";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "redirect:http://localhost:8002/error.html";

    }
}
